package com.example.stringbufferlogger.controller;

import com.example.stringbufferlogger.Utils.Base64ToMultipartFileUtil;
import com.example.stringbufferlogger.dto.LogEntryDTO;
import com.example.stringbufferlogger.service.FileService;
import com.example.stringbufferlogger.service.LogReceiverService;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/log")
public class FileLogController {

    // 配置保存目录
//    private static final String UPLOAD_DIR = "uploads/";
//    private static final String DOWNLOAD_DIR = "downloads/";
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private LogReceiverService logReceiverService;
    @Autowired
    private FileService fileService; // 注入 FileService



    @PostMapping("/save")
    public ResponseEntity<Map<String, Object>> handleLogData(@RequestBody Map<String, Object> logData) {
        Map<String, Object> response = new HashMap<>();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        try {
            // 1. 保存基本日志信息
            System.out.println("Received log: " + logData);

            // 2. 处理上传文件
            if (logData.containsKey("uploadFiles")) {
                processUploadFiles(logData.get("uploadFiles"), (String) logData.get("requestId"), logData.get("path").toString());
            }

            // 3. 处理下载文件
            if (logData.containsKey("downloadFile")) {
                processDownloadFile(logData.get("downloadFile"), (String) logData.get("requestId"), logData.get("path").toString());
            }
            //4.保存日志入库
            receiveLog(logData);

            response.put("status", "success");
            response.put("message", "Log and files processed successfully");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "Error processing log: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 处理上传文件
     *
     * @param interfaceUrl url
     * @return
     */
    public void processUploadFiles(Object uploadFilesData, String reqId, String interfaceUrl) throws IOException {
        if (uploadFilesData instanceof Map) {
            Map<?, ?> uploadFilesMap = (Map<?, ?>) uploadFilesData;
            Integer fileCount = (Integer) uploadFilesMap.get("fileCount");

            if (fileCount != null && fileCount > 0) {
                List<?> files = (List<?>) uploadFilesMap.get("files");

                for (Object fileObj : files) {
                    if (fileObj instanceof Map) {
                        Map<?, ?> fileInfo = (Map<?, ?>) fileObj;
                        String oriFileName = (String) fileInfo.get("name");
                        String base64Content = (String) fileInfo.get("content");

                        // 使用工具类将 Base64 内容转换为 MultipartFile 对象
                        MultipartFile multipartFile = Base64ToMultipartFileUtil.convert(base64Content, oriFileName);

                        // 调用 FileService 的 handleFileUpload 方法
                        fileService.handleFileUpload(multipartFile, (String) reqId, interfaceUrl);
                    }
                }
            }
        }
    }



    /**
     * 处理下载文件
     *
     * @param interfaceUrl url
     * @return
     */
    private void processDownloadFile(Object downloadFileData, String reqId, String interfaceUrl) throws IOException {
        if (downloadFileData instanceof Map) {
            Map<?, ?> downloadFileMap = (Map<?, ?>) downloadFileData;
            String orgFileName = (String) downloadFileMap.get("fileName");
            String base64Content = (String) downloadFileMap.get("content");
            if (orgFileName != null && base64Content != null) {
                // 使用工具类将 Base64 内容转换为 MultipartFile 对象
                String fileName = insertSuffix(orgFileName, reqId);
                MultipartFile multipartFile = Base64ToMultipartFileUtil.convert(base64Content, fileName);

                // 构建 metadataJson
                String metadataJson = String.format("{\"fileName\":\"%s\", \"contentType\":\"application/octet-stream\", \"size\":%d}",
                        fileName, multipartFile.getSize());

                // 调用 FileService 的 receiveDownload 方法
                ResponseEntity<Map<String, Object>> response = fileService.receiveDownload(multipartFile, metadataJson, reqId, interfaceUrl);
                if (response.getStatusCode().isError()) {
                    System.err.println("文件上传到 OSS 失败: " + response.getBody());
                }
            }
        }
    }

    public void receiveLog(Map<String, Object> logEntry) {

//             1. 处理日志数据（这里简单打印，实际可存入数据库或发送到日志系统）
        System.out.println("收到日志: {}" + logEntry.toString());
        LogEntryDTO logEntryDTO = objectMapper.convertValue(logEntry, LogEntryDTO.class);
        logEntryDTO.setReplayStatus(logEntry.get("replaystatus").toString());

        try {
            logReceiverService.LogRecord(logEntryDTO);
        } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
            System.err.println("调用 LogRecord 方法时发生异常，异常信息: " + e.getMessage());
            // 可以根据实际需求添加更多的异常处理逻辑，例如记录日志到文件
        }
    }

    private String insertSuffix(String fileName, String ruqid) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0) {
            String extension = ruqid + fileName.substring(dotIndex); // 获取 .xls
            return extension;
        } else {
            System.out.println("文件没有扩展名");
        }
        return fileName;
    }
}